package com.dream.testtubebaby_doctor.fragment;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.dream.testtubebaby_doctor.ChatMessageActivity;
import com.dream.testtubebaby_doctor.R;
import com.dream.testtubebaby_doctor.adapter.MyChatListAdapter;
import com.dream.testtubebaby_doctor.data.chat.ChatJsonParser;
import com.dream.testtubebaby_doctor.data.chat.ChatListItem;
import com.dream.testtubebaby_doctor.okhttp.OkHttpClientManager;
import com.dream.testtubebaby_doctor.utils.AppUtil;
import com.dream.testtubebaby_doctor.utils.NetUtil;
import com.dream.testtubebaby_doctor.utils.SharePreferencesManager;
import com.dream.testtubebaby_doctor.utils.ToastUtil;
import com.dream.testtubebaby_doctor.view.xlistview.IXListViewLoadMore;
import com.dream.testtubebaby_doctor.view.xlistview.IXListViewRefreshListener;
import com.dream.testtubebaby_doctor.view.xlistview.XListView;

public class ConsultationFragment extends Fragment implements
		IXListViewRefreshListener, IXListViewLoadMore {
	public static final String CHAT_RECEIVER_ACTION = "com.doctor.chat.action";
	private static final int LOAD_MORE = 0x110;
	private static final int LOAD_REFREASH = 0x111;
	public static final int TIP_ERROR_NO_NETWORK = 0X112;
	public static final int TIP_ERROR_SERVER = 0X113;
	private static final int HANDER_REFREASH = 0x114;
	// private static final int download_step = 10;
	public boolean isLoadingDataFromNetWork;
	private DoctorChatReveiver mDoctorChatReveiver;
	private XListView xListView;
	private MyChatListAdapter mMyChatListAdapter;
	private List<ChatListItem> mDatas = new ArrayList<ChatListItem>();
	private List<ChatListItem> mDatasTemp = new ArrayList<ChatListItem>();
	private SharePreferencesManager mshSharePreferencesManager;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HANDER_REFREASH:
				mMyChatListAdapter.notifyDataSetChanged();
				break;

			default:
				break;
			}
		};
	};
	private View rootView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (rootView == null) {
			rootView = inflater.inflate(R.layout.fragment_my_chat_list, null);
			mshSharePreferencesManager = new SharePreferencesManager(
					getActivity());
			initListView(rootView);
			mDoctorChatReveiver = new DoctorChatReveiver();
			IntentFilter filter = new IntentFilter();
		    filter.addAction(CHAT_RECEIVER_ACTION);
		    getActivity().registerReceiver(mDoctorChatReveiver, filter);
		}
		ViewGroup parent = (ViewGroup) rootView.getParent();
		if (parent != null) {
			parent.removeView(rootView);
		}
		return rootView;
	}

	private void initListView(View view) {
		xListView = (XListView) view.findViewById(R.id.mychat_listview);
		mMyChatListAdapter = new MyChatListAdapter(getActivity(), mDatas,
				R.layout.chat_list_item_view);
		xListView.setAdapter(mMyChatListAdapter);
		xListView.setPullRefreshEnable(this);
		xListView.setPullLoadEnable(this);
		xListView.setRefreshTime(AppUtil.getRefreashTime(getActivity(), 0));
		xListView.startRefresh();
		xListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position > 0) {
					Intent intent = new Intent(getActivity(),
							ChatMessageActivity.class);
					long touserid = mDatas.get(position - 1).getId();
					intent.putExtra(ChatMessageActivity.TO_USER_ID, touserid);
					intent.putExtra(ChatMessageActivity.GROUP_ID_KEY, mDatas.get(position - 1).getGroup_id());
					intent.putExtra(ChatMessageActivity.CHAT_TITLE_KEY, mDatas.get(position - 1).getTitle());
					startActivity(intent);
				}
			}

		});
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unregisterReceiver(mDoctorChatReveiver);
	}
	
	@Override
	public void onLoadMore() {
		new LoadDatasTask().execute(LOAD_MORE);
	}

	@Override
	public void onRefresh() {
		new LoadDatasTask().execute(LOAD_REFREASH);
	}

	class LoadDatasTask extends AsyncTask<Integer, Void, Integer> {

		@Override
		protected Integer doInBackground(Integer... params) {
			switch (params[0]) {
			case LOAD_MORE:
				loadMoreData();
				break;
			case LOAD_REFREASH:
				return refreashData();
			}
			return -1;
		}

		@Override
		protected void onPostExecute(Integer result) {
			switch (result) {
			case TIP_ERROR_NO_NETWORK:
				ToastUtil.toast(getActivity(), R.string.newwork_connect_error);
				break;
			case TIP_ERROR_SERVER:
				ToastUtil.toast(getActivity(), R.string.server_error);
				break;

			default:
				break;

			}

			xListView.setRefreshTime(AppUtil.getRefreashTime(getActivity(), 0));
			xListView.stopRefresh();
			xListView.stopLoadMore();
			mDatas.clear();
			mDatas.addAll(mDatasTemp);
			// mHandler.sendEmptyMessage(HANDER_REFREASH);
		}

	}

	protected void loadMoreData() {
		if (isLoadingDataFromNetWork) {
			try {
				if (mMyChatListAdapter.getCount() != 0) {
					ChatListItem chatListItem = (ChatListItem) mMyChatListAdapter
							.getItem(mMyChatListAdapter.getCount() - 1);
					if (chatListItem.getId() != 1) {
						// List<ChatListItem> newsItems =
						// downLoadMyChatListItem();
						// mDatas.addAll(newsItems);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	protected int refreashData() {
		if (NetUtil.checkNet(getActivity())) {
			try {
				List<ChatListItem> newsItems = downLoadMyChatListItem();
				// mMyChatListAdapter.setDatas(newsItems);
				mDatasTemp.clear();
				mDatasTemp.addAll(newsItems);
				isLoadingDataFromNetWork = true;
				AppUtil.setRefreashTime(getActivity(), 0);
			} catch (Exception e) {
				e.printStackTrace();
				isLoadingDataFromNetWork = false;
				return TIP_ERROR_SERVER;
			}
		} else {
			isLoadingDataFromNetWork = false;
			return TIP_ERROR_NO_NETWORK;
		}
		return -1;
	}

	private List<ChatListItem> downLoadMyChatListItem() {
		try {
			long uid = mshSharePreferencesManager.readUserId();
			List<ChatListItem> chatListItems = new ArrayList<ChatListItem>();
			// {"result":0,"chatobj":[{"uid":"8","objName":"tc2002"},{"uid":"17","objName":"eeee"}]}
			String content = OkHttpClientManager.postAsString(
					OkHttpClientManager.BASEURL
							+ "m=Home&c=App&a=searchChatObj",
					new OkHttpClientManager.Param("uid", String.valueOf(uid)));
			JSONObject obj;
			try {
				obj = new JSONObject(content);
				if (obj != null) {
					int result = obj.getInt("result");
					if (result == 0) {
						JSONArray jsonChat = new JSONArray(
								obj.getString("chatobj"));
						for (int i = 0; i < jsonChat.length(); i++) {
							JSONObject jsonObject = (JSONObject) jsonChat
									.get(i);
							ChatListItem chatListItem = ChatJsonParser
									.getMyChatItemNode(jsonObject);
							chatListItems.add(chatListItem);
						}
					}
				}
				return chatListItems;
			} catch (JSONException e) {
				e.printStackTrace();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private class DoctorChatReveiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(CHAT_RECEIVER_ACTION)){
				xListView.startRefresh();
			}
		}
		
	}
}
